#include "plogger.h"

#include "QDebug"

PLogger::PLogger(
        QObject *parent,
        const QString& fileName,
        const QString& appName,
        QPlainTextEdit *editor
        ) :
    QObject(parent)
{

    m_appName = appName;
    m_showAppName = true;

    m_editor = editor;
    m_showDate = true;
    if (!fileName.isEmpty())
    {
        m_file = new QFile;
        m_file->setFileName(fileName);
        m_file->open(QIODevice::Append | QIODevice::Text);

        QTextStream out(m_file);
        out.setCodec("UTF-8");
        if (m_file != 0)
        {
            out << m_lineStart() << endl;
        }
        if (m_editor != 0)
            m_editor->appendPlainText(m_lineStart());
    }
}

PLogger::~PLogger()
{
    write(tr("(PLogger) [EXE]: Chiuso il file di LOG: %1").arg(m_file->fileName()));
    if (m_file != 0)
        m_file->close();
}

void PLogger::write(const QString &value)
{
    QString text = ": " + value; // + "";

    if (m_showDate)
        text = QDateTime::currentDateTime().toString("[dd.MM.yyyy]-[hh:mm:ss] ") + text;

    if (m_showAppName)
        text = "(" + m_appName + ") "+ text;

    QTextStream out(m_file);
    out.setCodec("UTF-8");

    if (m_file != 0)
    {
        out << text << endl;
    }
    if (m_editor != 0)
        m_editor->appendPlainText(text);
}

void PLogger::setShowDateTime(bool value)
{
    m_showDate = value;
}

void PLogger::setShowAppName(bool value)
{
    m_showAppName = value;
}

QString PLogger::m_lineStart( void )
{
    QString s;
    return s.fill('-',80);
}
